package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.github.florent37.viewanimator.ViewAnimator;
import com.huantansheng.easyphotos.setting.Setting;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.widget.MyVideoPlayer;

import java.io.File;
import java.util.List;

/**
 * 大图预览界面图片集合的适配器
 * Created by huan on 2017/10/26.
 */
public class PhotosAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "PhotosAdapter";
    private List<Message> messageList;
    private OnClickListener listener;
    private LayoutInflater inflater;
    private Context context;
    private Info fromInfo;
    private boolean fromInfoUsed;


    public interface OnClickListener {
        Info onGetImageRectInfo(int position);
    }

    public PhotosAdapter(Context cxt, List<Message> photos, OnClickListener listener) {
        context = cxt;
        this.messageList = photos;
        this.inflater = LayoutInflater.from(cxt);
        this.listener = listener;
    }


    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == Constant.IM_TYPE_IMAGE) {
            return new PhotosViewHolder(inflater.inflate(R.layout.tx_item_big_picture, parent, false));
        } else {
            return new VideoViewHolder(inflater.inflate(R.layout.tx_item_video, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {

        //想仅对 缩小了的item 设置 不可复用，但是 偶尔还是会出现大图位置显示错位，暂时全部设置为 不可复用
         holder.setIsRecyclable(false);
        Message message = messageList.get(position);
        if (holder instanceof PhotosViewHolder) {
            PhotosViewHolder viewHolder = (PhotosViewHolder) holder;
            viewHolder.tv_photoCount.setText(position + 1 + "/" + messageList.size());
            String localPath;
            if (!TextUtils.isEmpty(message.getLocalFilePath())) {
                //发送的消息
                localPath = message.getLocalFilePath();
            } else {
                //收到的消息，或者是一条  目前属于发送消息，但是其实是一条 转发于 收到的  消息
                String imageKey = message.getContent();
                localPath = Helper.getInstance().getFilePath() + File.separator + imageKey;
            }
            //开启缩放功能
            viewHolder.ivPhoto.enable();
            viewHolder.ivPhoto.setAnimaDuring(400);
            //Glide.with(context).load(localPath).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.ivPhoto);
            GlideLoadUtils.glideLoad(context,localPath,viewHolder.ivPhoto);
            if (fromInfo != null && !fromInfoUsed) {
//                holder.setIsRecyclable(false);
                fromInfoUsed = true;
               viewHolder.ivPhoto.animaFrom(fromInfo);

            }
            final int type = message.getSubType();
            viewHolder.ivPlay.setVisibility(View.GONE);
            if (type == Constant.IM_TYPE_VIDEO) {

                viewHolder.ivPlay.setVisibility(View.VISIBLE);
                viewHolder.ivPlay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //toPlayVideo(v, localPath, type);
                    }
                });
            }

            viewHolder.ivPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewHolder.ivPhoto.setOnClickListener(null);
                    Info info = listener.onGetImageRectInfo(position);
                    viewHolder.tv_photoCount.setVisibility(View.INVISIBLE);
                    if (info != null) {
                        //想仅对 缩小了的item 设置 不可复用，但是 偶尔还是会出现大图位置显示错位，暂时全部设置为 不可复用

                        ViewAnimator.animate(viewHolder.rlTitle).alpha(1, 0).duration(400).start();
                        bigImageAnimateOut(info, viewHolder.ivPhoto);
                    } else {
                        Log.e(TAG, "onClick: 获取小图消息失败 position：" + position);
                    }
                }
            });

        } else if (holder instanceof VideoViewHolder) {
            VideoViewHolder videoViewHolder = (VideoViewHolder) holder;
            String videoPath;
            String localFilePath = message.getLocalFilePath();
            if (TextUtils.isEmpty(localFilePath)) {
                videoPath = Helper.getInstance().getFilePath() + File.separator + message.getContent();
            } else {
                //原始发送消息 或者 转发于某条 发送消息
                videoPath = localFilePath;
            }
            videoViewHolder.videoPlayer.init(videoPath, videoPath);
            videoViewHolder.videoPlayer.ivBack.setOnClickListener(v -> {

                Info info = listener.onGetImageRectInfo(position);


            });
        }


    }

    public void bigImageAnimateOut(Info info, final PhotoView photoView) {

//        photoView.animaTo(info, new Runnable() {
//            @Override
//            public void run() {
//                //reSet();
//                photoView.animaFrom(info);
//            }
//        });


        Info bigImageViewInfo = PhotoView.getBigImageViewInfo(photoView);
        RectF bigImageRectF = bigImageViewInfo.getmImgRect();
        RectF smallRectF = info.getmImgRect();
        float scaleX = smallRectF.width() / bigImageRectF.width();
        float scaleY = smallRectF.height() / bigImageRectF.height();
        float translationY = bigImageViewInfo.getmRect().centerY() - info.getmRect().centerY();
        float translationX = bigImageViewInfo.getmRect().centerX() - info.getmRect().centerX();
        ViewAnimator.animate(photoView).scaleX(scaleX).scaleY(scaleY).translationY(0, -translationY).translationX(0, -translationX).duration(400).start();


    }

    private void toPlayVideo(View v, String path, String type) {
        Context context = v.getContext();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = getUri(context, path, intent);
        intent.setDataAndType(uri, type);
        context.startActivity(intent);
    }

    private Uri getUri(Context context, String path, Intent intent) {
        File file = new File(path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            return FileProvider.getUriForFile(context, Setting.fileProviderAuthority, file);
        } else {
            return Uri.fromFile(file);
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public void setFromInfo(Info fromInfo) {
        this.fromInfo = fromInfo;
        fromInfoUsed = false;
    }

    public class PhotosViewHolder extends RecyclerView.ViewHolder {
        PhotoView ivPhoto;
        ImageView ivPlay;
        TextView tv_photoCount;
        View rlTitle;

        PhotosViewHolder(View itemView) {
            super(itemView);
            ivPhoto = itemView.findViewById(R.id.iv_picture);
            ivPlay = itemView.findViewById(R.id.iv_play);
            tv_photoCount = itemView.findViewById(R.id.tv_title);
            rlTitle = itemView.findViewById(R.id.container);
        }
    }


    public class VideoViewHolder extends RecyclerView.ViewHolder {

        MyVideoPlayer videoPlayer;

        public VideoViewHolder(@NonNull View itemView) {
            super(itemView);
            videoPlayer = itemView.findViewById(R.id.video_player);
        }
    }
}
